#include "gffmpeg.h"

int lua_ffmpeg_render(lua_State *L){
	VideoState *is = *(VideoState **)luaL_checkudata(L, 1, "gge_gffmpeg");
	if (is)
	{
		double remaining_time = 0.0;
		if (is->show_mode != SHOW_MODE_NONE  && !is->eof  && (!is->paused || is->force_refresh))
			video_refresh(is, &remaining_time);
		lua_pushboolean(L,is->eof);
		
		return 1;
	}
	return 0;
}

int lua_ffmpeg_open(lua_State *L){
	const char* file = luaL_checkstring(L,1);
	VideoState *is,**ud;

	is = stream_open(file,NULL);
	if (!is)
		return 0;

	ud = (VideoState **)lua_newuserdata(L,sizeof(VideoState *));
	*ud = is;
	luaL_setmetatable(L,"gge_gffmpeg");
	return 1;
}

int lua_ffmpeg_close(lua_State *L){
	VideoState **ud = (VideoState **)luaL_checkudata(L, 1, "gge_gffmpeg");
	if (*ud)
	{
		stream_close(*ud);
		*ud = NULL;
	}
	return 0;
}

int lua_ffmpeg_init(lua_State* L) {
	SDL_Window** win = (SDL_Window**)luaL_checkudata(L, 1, "SDL_Window");
	int w, h;

	SDL_GetWindowSize(*win, &w, &h);
	screen_width = w;
	screen_height = h;
	renderer = SDL_GetRenderer(*win);

	av_init_packet(&flush_pkt);
	flush_pkt.data = (uint8_t*)&flush_pkt;

	lua_pushcfunction(L, lua_ffmpeg_open);
	return 1;
}


LUALIB_API int luaopen_gffmpeg(lua_State* L){
	
	luaL_Reg methods[] = {
		{"__gc", lua_ffmpeg_close},
		{"render", lua_ffmpeg_render},
		{"close", lua_ffmpeg_close},
		{NULL, NULL},
	};
	//setvbuf(stdout, NULL, _IONBF, 0);
	luaL_newmetatable(L, "gge_gffmpeg");
	luaL_setfuncs(L,methods,0);
	lua_pushvalue(L,-1);
	lua_setfield(L, -2, "__index");
	lua_pop(L,1);

	lua_pushcfunction(L, lua_ffmpeg_init);
	return 1;
}